package cn.com.wms.Base;


import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wms.util.SerializationUtils;

public class RedisDAO   {

	private static Logger logger = LoggerFactory.getLogger(RedisDAO.class);
	/**
	 * shiro-redis的session对象前缀
	 */
	private final String REDIS_SESSION_PRE = "redis_session:";

	private RedisManager redisManager;
    private int timeOut=1800000;//默认30分钟

	public void update(String sessionid,String userName)  {
		this.save(sessionid,userName);
	}

	/**
	 * save session
	 *
	 * @param session
	 * @throws UnknownHttpSessionException
	 */
	private void save(String sessionid,String userName)  {
		if (userName == null) {
			logger.error("userName or userName id is null");
			return;
		}

		byte[] key = getByteKey(sessionid);
		byte[] value = SerializationUtils.serialize(userName);


		int expire =timeOut/1000;

		this.redisManager.set(key, value, expire);
	}


	public void delete(String sessionid) {
		if (sessionid == null) {
			logger.error("userName or userName id is null");
			return;
		}
		redisManager.del(this.getByteKey(sessionid));

	}


	public Collection<String> getActives() {
		Set<String> userNames = new HashSet<String>();

		Set<byte[]> keys = redisManager.keys(this.REDIS_SESSION_PRE + "*");
		if (keys != null && keys.size() > 0) {
			for (byte[] key : keys) {
				String s = (String) SerializationUtils.deserialize(redisManager.get(key));
				userNames.add(s);
			}
		}

		return userNames;
	}




	public String doRead(Serializable sessionId) {
		if (sessionId == null) {
			logger.error("userName id is null");
			return null;
		}

		String s = (String) SerializationUtils.deserialize(redisManager.get(this.getByteKey(sessionId)));

		return s;
	}

	/**
	 * 获得byte[]型的key
	 *
	 * @param key
	 * @return
	 */
	private byte[] getByteKey(Serializable sessionid) {
		String preKey = this.REDIS_SESSION_PRE + sessionid;
		return preKey.getBytes();
	}

	public RedisManager getRedisManager() {
		return redisManager;
	}

	public void setRedisManager(RedisManager redisManager) {
		this.redisManager = redisManager;

		/**
		 * 初始化redisManager
		 */
		this.redisManager.init();
	}

	public int getTimeOut() {
		return timeOut;
	}

	public void setTimeOut(int timeOut) {
		this.timeOut = timeOut;
	}


}
